package src.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NIOSocketServerIO {
    public static void main(String[] args) throws InterruptedException {
        try {
            ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(8081));
            while (true){

                SocketChannel socketChannel=serverSocketChannel.accept();
                if (socketChannel!=null){
                    ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                    socketChannel.read(byteBuffer);
                    System.out.println(new String(byteBuffer.array()));
                    Thread.sleep(10000L);
                    byteBuffer.flip();
                    byteBuffer.put("我是服务器".getBytes());
                    socketChannel.write(byteBuffer);

                }else {
                    Thread.sleep(2000L);
                    System.out.println("没有连接过来");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
